const express = require('express');
const Wifi = require('./wifi-connection');
const bodyParser = require('body-parser')
const fs = require('fs');
const path = require('path');

const {
	getLocalIps
} = require('../mdns')
const {
	PromisifyExec
} = require('../lib')
// create application/json parser
const jsonParser = bodyParser.json()

const wifi = new Wifi();

const router = express.Router();

// wpa_cli list_networks -i wlan0
// wpa_cli remove_network -i wlan0 0

/*
router.use('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  next();
});

*/

let db
(async () => {
	const { LowSync, JSONFileSync } = await import('lowdb')
	db = new LowSync(new JSONFileSync(path.join(__dirname, '../../config.json')))
	try {
		db.read()
		console.log(db)
	} catch (error) {
		db.data = { wifi: {}, env: { lang: 'zh' } };
		db.write()
	}
})();

router.use('/', express.static(__dirname))

router.get('/', (req, res) => {
	var form = fs.readFileSync(path.join(__dirname, 'index.html'), {
		encoding: 'utf8'
	});
	res.send(form);
})

router.get('/info', function (req, res) {
	wifi.getStatus().then(info => res.json(info))
})

router.get('/ips', async function (req, res) {
	res.json(await getLocalIps())
})

router.post('/connect', jsonParser, function (req, res) {
	// console.log(req.headers)
	const request = req.body
	request.timeout = 20000
	console.log(req.body)
	if (db) {
		db.data.wifi[request.ssid] = request.psk
		db.write()
	}
	if (request && request.ssid) {
		// echo "jszc2019" | sudo nmcli --ask dev wifi connect  JSZC
		PromisifyExec(`echo "${request.psk}" | sudo nmcli --ask dev wifi connect  "${request.ssid}"`).then(() => {
			// wifi.connect(request).then(() => {
			wifi.getStatus().then(info => {
				// console.log(status)
				info.status = 'OK'
				info.status_code = 1
				res.json(info)
			})

		}).catch((error) => {
			console.log(error);
			res.json({
				status: 'error',
				status_code: 0
			})
		});
	} else {
		res.json({
			status: 'error',
			status_code: 101
		})
	}
})

router.get('/scan', function (req, res) {
	wifi.scan().then(result => {
		if (db) {
			res.json(result.map(wifi => {
				if (db.data.wifi[wifi.ssid]) {
					wifi.psk = db.data.wifi[wifi.ssid]
				}
				return wifi
			}))
		} else {
			res.json(result)
		}
	})
})

module.exports = router;